<template>
    <view class="overall">
        <view class="content">
            <wd-notice-bar text="仅支持查询一年内的缴费记录" prefix="warn-bold" />
            <view class="switch">
                <view>
                    <view>{{userInfo.nickname}}</view>
                    <view>就诊人ID：{{userInfo.id}}</view>
                </view>
                <view>
                    <view @click="exchanging">切换就诊人</view>
                </view>
            </view>
            <wd-status-tip v-if="logItem.length === 0 && (!moneyIndexData || !moneyIndexData.data || moneyIndexData.data.length === 0)" image="content" tip="暂无内容" />

            <!-- 原有缴费记录列表 -->
            <view class="manifest" v-for="(item, index) in logItem" :key="index" @click="details(item)">
                <view>
                    <view>就诊科室</view>
                    <view>{{item.depart_id}}</view>
                </view>
                <view>
                    <view>缴费金额</view>
                    <view style="display: flex;align-items: center;">
                        <view style="color: #FF6010;margin-right: 3rpx;">￥{{item.money}}</view>
                        <wd-icon name="arrow-right" size="22px"></wd-icon>
                    </view>
                </view>
                <view>
                    <view>缴费时间</view>
                    <view>{{item.create_time}}</view>
                </view>
            </view>

            <!-- 新增的缴费记录列表（每组数据独立渲染） -->
            <view 
                class="manifest" 
                v-for="(item, index) in moneyIndexData?.data || []" 
                :key="item.id" 
                @click="details(item)"
            >
                <view>
                    <view>就诊科室</view>
                    <view>内科</view> <!-- 固定为内科 -->
                </view>
                <view>
                    <view>缴费金额</view>
                    <view style="display: flex;align-items: center;">
                        <view style="color: #FF6010;margin-right: 20rpx;">￥{{item.money}}</view>
                        <wd-icon name="arrow-right" size="22px"></wd-icon>
                    </view>
                </view>
                <view>
                    <view>缴费时间</view>
                    <view>{{today}}</view> <!-- 固定为今天 -->
                </view>
            </view>
        </view>

        <!-- 原生弹窗实现 -->
        <view class="modal-mask" v-if="show" @click="handleClose"></view>
        <view class="modal-container" v-if="show">
            <view class="person">
                <view class="personTitle">
                    <view>切换就诊人</view>
                </view>
                <view class="personItem" v-for="(item, index) in cardInfo" :key="index" @click="substitution(item)">
                    <view>{{item.nickname}}</view>
                    <view>就诊ID号：{{item.id}}</view>
                </view>
                <view class="personBut">
                    <view @click="manage(1)">添加就诊人</view>
                    <view @click="manage(2)">管理就诊人</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script lang="ts" setup>
    import { ref, onMounted, computed } from 'vue';
    import { card, payLogs, lists, rechargeable } from '@/api/index.js'; // 导入封装的接口

    // 响应式数据
    const userInfo = ref({});
    const cardInfo = ref([]);
    const logItem = ref([]);
    const department = ref([]);
    const number = ref(0);
    const show = ref(false);
    const moneyIndexData = ref(null); // 存储money/index接口响应数据
    const visitData = ref(null); // 存储新接口的响应数据

    // 计算属性：获取今天的日期（格式：YYYY-MM-DD）
    const today = computed(() => {
        const date = new Date();
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    });

    // 从本地存储获取user数据
    const getUserData = () => {
        try {
            const user = uni.getStorageSync('user');
            console.log('本地存储的user数据:', user);
            return user;
        } catch (e) {
            console.error('获取本地存储失败:', e);
            return null;
        }
    };

    // 调用封装的rechargeable接口获取缴费记录
    const fetchMoneyIndex = async (cardValue) => {
        if (!cardValue) {
            console.warn('card参数为空，无法请求money/index接口');
            return;
        }

        try {
            console.log(`开始请求money/index接口，参数card: ${cardValue}`);
            const res = await rechargeable({ card: cardValue });
            console.log('money/index接口响应成功！');
            console.log('money/index接口返回的data:', res.data);
            moneyIndexData.value = res.data;
        } catch (error) {
            console.error('money/index接口请求失败:', error);
        }
    };

    // 调用封装的card接口（实际为Visit/index）并打印响应
    const fetchVisitData = async (userId) => {
        if (!userId) {
            console.warn('user_id参数为空，无法请求Visit/index接口');
            return;
        }

        try {
            console.log(`开始请求Visit/index接口，参数user_id: ${userId}`);
            const res = await card({ user_id: userId });
            console.log('Visit/index接口响应成功！状态码:', res.statusCode || '未知(封装后)');
            console.log('Visit/index接口返回的data:', res.data);
            visitData.value = res.data;

            // 从新接口数据中提取card值，调用money/index接口
            if (res.data && res.data.data && Array.isArray(res.data.data) && res.data.data.length > 0) {
                const newCardValue = res.data.data[0].card; // 获取第一条数据的card值
                console.log('从Visit/index接口提取的card值:', newCardValue);
                fetchMoneyIndex(newCardValue); // 使用新card值请求money/index接口
            } else {
                console.warn('Visit/index接口返回数据格式不符合预期，无法提取card值');
            }
        } catch (error) {
            console.error('Visit/index接口请求失败:', error);
        }
    };

    // 初始化数据
    const initData = () => {
        const userData = getUserData();
        if (!userData || !userData.data) {
            console.error('未找到有效的user数据');
            return;
        }

        // 提取用户ID，调用新接口（Visit/index）
        const userId = userData.data.id;
        if (userId) {
            fetchVisitData(userId); // 先请求新接口获取card值
            fetchCardList(userId);
            fetchPayLogs(userId);
        }
        fetchDepartmentList();
    };

    // 获取就诊人列表
    const fetchCardList = async (userId) => {
        try {
            const res = await card({ user_id: userId });
            cardInfo.value = res.data || [];
            const defaultCard = cardInfo.value.find(item => item.status === 1) || cardInfo.value[0];
            if (defaultCard) userInfo.value = defaultCard;
        } catch (e) {
            console.error('获取就诊人列表失败:', e);
        }
    };

    // 获取科室列表
    const fetchDepartmentList = async () => {
        try {
            const res = await lists({});
            department.value = res.data[0]?.childrens || [];
        } catch (e) {
            console.error('获取科室列表失败:', e);
        }
    };

    // 获取缴费记录
    const fetchPayLogs = async (userId) => {
        try {
            const res = await payLogs({ user_id: userId });
            logItem.value = res.data || [];
        } catch (e) {
            console.error('获取缴费记录失败:', e);
        }
    };

    // 页面加载时执行
    onMounted(() => {
        initData();
    });

    // 切换就诊人
    const exchanging = () => {
        show.value = true;
    };

    const handleClose = () => {
        show.value = false;
    };

    // 切换就诊人后重新请求接口
    const substitution = (item) => {
        userInfo.value = item;
        handleClose();
        // 切换就诊人时，重新请求新接口获取对应card值
        const userId = item.id;
        if (userId) {
            fetchVisitData(userId);
        }
    };

    const details = (item) => {
        uni.setStorageSync('checklist', item);
        uni.navigateTo({ url: '/pages/examine/examine' });
    };

    const manage = (index) => {
        show.value = false;
        uni.navigateTo({
            url: index === 1 ? '/pages/founded/founded' : '/pages/patient/patient'
        });
    };
</script>

<style scoped>
    .overall {
        width: 100%;
        background-color: #F4F4F4;
        min-height: 100vh;
    }

    .content {
        width: 100%;
    }

    .switch {
        width: 94%;
        height: 200rpx;
        padding: 0 3%;
        background-color: white;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20rpx;
    }

    .switch>view:first-child>view {
        padding-bottom: 18rpx;
    }

    .switch>view:first-child>view:first-child {
        font-weight: bold;
        font-size: 36rpx;
    }

    .switch>view:last-child>view {
        color: #40C5D3;
        border: 3rpx #40C5D3 solid;
        padding: 12rpx 20rpx;
        border-radius: 2000rpx;
        font-size: 30rpx;
    }

    /* 缴费记录组样式（每组独立） */
    .manifest {
        width: 100%;
        background-color: white;
        padding: 20rpx 0;
        margin-bottom: 20rpx;
        border-radius: 10rpx; /* 增加圆角区分每组 */
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05); /* 轻微阴影增强分组感 */
    }

    .manifest>view {
        display: flex;
        width: 92%;
        height: 80rpx;
        align-items: center;
        margin-left: 4%;
        margin-right: 4%;
        justify-content: space-between;
        border-bottom: 1rpx solid #F5F5F5; /* 组内字段分隔线 */
    }

    .manifest>view:last-child {
        border-bottom: none; /* 移除最后一个字段的分隔线 */
    }

    .person {
        width: 100vw;
        padding-bottom: 2vh;
    }

    .personTitle {
        width: 100%;
        height: 100rpx;
        background-color: #00DACA;
        display: flex;
        justify-content: center;
        align-items: center;
        color: white;
        font-weight: bold;
        font-size: 36rpx;
    }

    .personItem {
        width: 96%;
        padding: 30rpx 0%;
        margin: 0 2%;
        height: 100rpx;
        border-bottom: #C7C7C7 1rpx solid;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .personBut {
        width: 100%;
        height: 100rpx;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .personBut>view {
        width: 50%;
        height: 100rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 32rpx;
        color: #00A8BB;
        border-bottom: #C7C7C7 1rpx solid;
    }

    .modal-mask {
        position: fixed;
        z-index: 9998;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
    }

    .modal-container {
        position: fixed;
        z-index: 9999;
        bottom: 0;
        left: 0;
        width: 100%;
        background-color: #fff;
        border-radius: 20rpx 20rpx 0 0;
    }
</style>    